/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "tinyxml.h"
#include "hhdGfxDirector.h"
#include "hhdPhysics.h"
#include "hhdGfxPass.h"

#include "hhdGameObject.h"
#include "hhdMessenger.h"
#include "hhdContentLibrary.h"
#include "hhdLighting.h"
#include "hhdCCamera.h"
#include "hhdCPointLight.h"
#include "hhdCDirectionalLight.h"
#include "hhdCSpotLight.h"
#include "hhdCMeshRenderer.h"
#include "hhdMConstantBufferModifier.h"
#include "hhdGfxApi.h"

namespace hhd
{
    DirectorCPP(hhd::GfxDirector);

    const float GfxDirector::far_clip_radius = 20000.0f;

    GfxDirector::GfxDirector(void)
        : _pl_bin(max_lights_point)
        , _dl_bin(max_lights_directional)
        , _sl_bin(max_lights_spot)
        , _cull_frustrum(NULL)
        , _active_camera(NULL)
    {
    }

    GfxDirector::~GfxDirector(void)
    {
    }

    void GfxDirector::handle_culling_message(IMessageReceiver* receiver, IMessage* message)
    {
        GfxDirector* _this = (GfxDirector*)(receiver);

        CullingMessage* cull_message = message->as<CullingMessage>();
        const ArrayList<GameObject*>& nonculled_objects = cull_message->getGameObjects();

        //clear our non culled objects
        _this->_nonculled_components.clear();
        for(size_t i = 0; i < nonculled_objects.size(); i++)
        {
            GameObject* go = nonculled_objects[i];
            int count = go->componentCount();

            for(int j = 0; j < count; j++)
            {
                if(CMeshRenderer* mr =  go->getComponent(j)->as<CMeshRenderer>())
                {
                    _this->_nonculled_components.add(mr);
                }
                if(CPointLight* pl = go->getComponent(j)->as<CPointLight>())
                {
                    _this->_nonculled_components.add(pl);
                }
                if(CSpotLight* sl = go->getComponent(j)->as<CSpotLight>())
                {
                    _this->_nonculled_components.add(sl);
                }
            }
        }
    }

    void GfxDirector::reset()
    {
        if(_cull_frustrum)
        {
            Messenger::unregisterReceiver<CullingMessage>(this, _cull_frustrum);
        }

        _lit_meshes.clear();

		IEnumerator< Pair< String, GfxRenderTargetSet* > >& enumeratorRTS = _gfx_render_target_sets.getEnumerator();
		while(enumeratorRTS.moveNext())
		{
			gfxDestroyRenderTargetSet( enumeratorRTS.current().second );
		}
		_gfx_render_target_sets.clear();

		IEnumerator< Pair< String, GfxRenderTarget* > >& enumeratorRT = _gfx_render_targets.getEnumerator();
		while(enumeratorRT.moveNext())
		{
			gfxDestroyRenderTarget( enumeratorRT.current().second );
		}
		_gfx_render_targets.clear();
    }

    // read in xml
    IDirector* GfxDirector::deserializeFromXML(const TiXmlElement* in_xml_element)
    {
		String type;
		int32_t result = in_xml_element->QueryStringAttribute("type", &type);
		HHD_ASSERT(result == TIXML_SUCCESS);
        HHD_ASSERT(String::equals(in_xml_element->Value(), "Director") && String::equals(type, "GfxDirector"));

		for(const TiXmlElement* element = in_xml_element->FirstChildElement();
			element != NULL;
			element = element->NextSiblingElement())
		{
			if(String::equals(element->Value(), "RenderTarget"))
			{
				deserializeRenderTargetFromXml(element);
			}
			else if(String::equals(element->Value(), "RenderTargetSet"))
			{
				deserializeRenderTargetSetFromXml(element);
			}
			else if(String::equals(element->Value(), "Pass"))
			{
				deserializePassFromXml(element);
			}
			else if(String::equals(element->Value(), "Content"))
			{
				deserializeMaterialFromXml(element);
			}
			else
			{
				HHD_ASSERT(!"Unknown child element found parsing GfxDirector xml.");
			}
		}

        return this;
    }

	void GfxDirector::deserializeRenderTargetFromXml( const TiXmlElement* in_xml_element )
	{
		HHD_ASSERT(String::equals(in_xml_element->Value(), "RenderTarget"));
		
		//parse
		String name(in_xml_element->Attribute("name"));

		GfxTexture2dConfig config;
		int32_t result;

		result = in_xml_element->QueryUnsignedIntAttribute("width", &config.width);
		HHD_ASSERT(result == TIXML_SUCCESS);

		result = in_xml_element->QueryUnsignedIntAttribute("height", &config.height);
		HHD_ASSERT(result == TIXML_SUCCESS);

		String format;
		result = in_xml_element->QueryStringAttribute("format", &format);
		HHD_ASSERT(result == TIXML_SUCCESS);
		config.format = GfxTexture2DFormatFromString(format);

		//create
		GfxRenderTarget* render_target;
		config.mip_count = 1;
		gfxCreateRenderTarget(render_target, config);

		_gfx_render_targets.add(name, render_target);
	}

	void GfxDirector::deserializeRenderTargetSetFromXml( const TiXmlElement* in_xml_element )
	{
		HHD_ASSERT(String::equals(in_xml_element->Value(), "RenderTargetSet"));

		//parse
		Vector<GfxRenderTarget*> render_targets;
		String name(in_xml_element->Attribute("name"));
		String render_target_name;

		for (const TiXmlElement* element = in_xml_element->FirstChildElement();
			element != NULL;
			element = element->NextSiblingElement())
		{
			HHD_ASSERT(String::equals(element->Value(), "RenderTarget"));

			int32_t result = element->QueryStringAttribute("name", &render_target_name);
			HHD_ASSERT(result == TIXML_SUCCESS);

			GfxRenderTarget* render_target;
			bool found = _gfx_render_targets.tryGetValue(render_target_name, render_target);
			HHD_ASSERT(found == true);
			render_targets.add( render_target );
		}

		GfxRenderTargetSet* render_target_set;
		gfxCreateRenderTargetSet(render_target_set, render_targets);
		_gfx_render_target_sets.add(name, render_target_set);
	}

	void GfxDirector::deserializePassFromXml( const TiXmlElement* in_xml_element )
	{

	}

	void GfxDirector::deserializeMaterialFromXml( const TiXmlElement* in_xml_element )
	{
		String content_type;
		int32_t content_result = in_xml_element->QueryStringAttribute("type", &content_type);
		HHD_ASSERT(content_result == TIXML_SUCCESS);
		HHD_ASSERT(String::equals(content_type, "GfxMaterial"));

		String material_path;
		content_result = in_xml_element->QueryStringAttribute("path", &material_path);
		HHD_ASSERT(content_result == TIXML_SUCCESS);

		SmartPtr<IContent> material = ContentLibrary::loadContent<GfxMaterial>(material_path);
		_gfx_materials.add( SmartPtr<IContent>::castTo<GfxMaterial>(material) );
	}

    void GfxDirector::initialize()
    {
        registerMessageCallback<CullingMessage>(GfxDirector::handle_culling_message);

        if( _active_camera &&
            (_cull_frustrum = _active_camera->getParentGameObject()->getComponentOfType<CullingFrustum>()) )
        {
            Messenger::registerReceiver<CullingMessage>(this, _cull_frustrum);
        }

    }

    void GfxDirector::update(const GameTimer& in_gt)
    {		
    }

    void GfxDirector::draw()
    {
        for(uint32_t i = 0; i < _gfx_passes.size(); i++)
        {
            GfxPass* pass = _gfx_passes[i];
            pass->Begin();
            pass->Draw();
            pass->End();
        }
    }

    void GfxDirector::setActiveCamera(CCamera* in_camera)
    {
        _active_camera = in_camera;
    }

    void GfxDirector::registerComponent(hhd::IComponent* in_component)
    {
        //check if it is a camera, set it to active camera. Last one to register
        //becomes the active one.
        if( in_component->is<CCamera>() )
        {
            _active_camera = (CCamera*) in_component;
        }
        //see if it is a light we need to hold onto
        else if( in_component->is<CPointLight>() )
        {
            _point_lights.add( (CPointLight*)in_component );
        }
        else if( in_component->is<CDirectionalLight>() )
        {
            _directional_lights.add( (CDirectionalLight*)in_component );
        }
        else if( in_component->is<CSpotLight>() )
        {
            _spot_lights.add( (CSpotLight*)in_component );
        }
        //look to see if it is a MeshRenderer and wants lighting info
        else if( in_component->is<CMeshRenderer>())
        {
            _registered_components.add( in_component );

            CMeshRenderer* mesh_renderer = in_component->as<CMeshRenderer>();
            //handle those that want lighting
            if( mesh_renderer->useLighting() )
            {
                _lit_meshes.add( mesh_renderer );
            }
            //handle those that don't
            else
            {
                _emissive_meshes.add( mesh_renderer );
                //pass the component on to each MeshProcess
            }
        }
#if GFX_AGNOSTICWORK
        else if(in_component->is<GUITexture>() || in_component->is<GUIButton>())
        {
            //_registered_components.add( in_component );

            GUIComponent* gui_component = (GUIComponent*) in_component;
        }
#endif
    }

    void GfxDirector::unregisterComponent(hhd::IComponent* in_component)
    {
        //check if it is a camera, set it to active camera. Last one to register
        //becomes the active one.

        //see if it is a light we need to hold onto
        if( in_component->is<CPointLight>() )
        {
            _point_lights.swapRemove((CPointLight*)in_component);
        }
        else if( in_component->is<CDirectionalLight>() )
        {
            _directional_lights.swapRemove( (CDirectionalLight*)in_component );
        }
        else if( in_component->is<CSpotLight>() )
        {
            _spot_lights.swapRemove( (CSpotLight*)in_component );
        }
        //look to see if it is a MeshRenderer and wants lighting info
        else if(CMeshRenderer* mesh_renderer = in_component->as<CMeshRenderer>())
        {
            if(_lit_meshes.contains(mesh_renderer))
            {
                _lit_meshes.remove(mesh_renderer);
            }
        }

#if GFX_AGNOSTICWORK
        else if(in_component->is<GUITexture>())
        {
            _registered_components.swapRemove( in_component );

            GUITexture* gui_texture = in_component->as<GUITexture>();
        }
#endif
    }

    void GfxDirector::binInFrustumPointLights( HashSet<void*>* in_nonculled_components )
    {
        _pl_bin.clear();
        //check if we have collided with each light, if we have, use it
        for(size_t i = 0; i < _point_lights.size(); i++)
        {
            if(in_nonculled_components->contains(_point_lights[i]))
            {
                _pl_bin.add(_point_lights[i]);
            }

            if(_pl_bin.size() >= max_lights_point)
            {
                break;
            }
        }
    }

    void GfxDirector::binInFrustumDirectionalLights( CCamera* in_camera)
    {
        _dl_bin.clear();
        //figure out DirectionalLight info
        if(_directional_lights.size() <= max_lights_directional)
        {
            //add each one then add black lights to the rest later
            for(size_t j = 0; j < _directional_lights.size(); j++)
            {
                _dl_bin.add( _directional_lights[j] );
            }
        }
        else
        {
            //there are more lights then we can send to the card so we
            //need to let the designer know there is an issue
            error("There are too many Directional Lights in the current Scene.");
        }

    }

    void GfxDirector::binInFrustumSpotLights( HashSet<void*>* in_nonculled_components )
    {
        _sl_bin.clear();
        //check if we have collided with each light, if we have, use it
        for(size_t i = 0; i < _spot_lights.size(); i++)
        {
            if(in_nonculled_components->contains(_spot_lights[i]))
            {
                _sl_bin.add(_spot_lights[i]);
            }

            if(_sl_bin.size() >= max_lights_spot)
            {
                break;
            }
        }

    }

    void GfxDirector::fillOutLighting(CCamera* _active_camera, HashSet<void*>* in_nonculled_components)
    {
        //update info
        binInFrustumDirectionalLights( _active_camera );
        binInFrustumPointLights( in_nonculled_components );
        binInFrustumSpotLights( in_nonculled_components );
    }

}